// src/utils/crudMethods.js
import { students, addStudent, deleteStudent, updateStudent } from "@/api/api.js"
export const fetchData = async function () {
    this.loading = true;

    try {
        const params = {
            pageNum: this.pageNum,
            pageSize: this.pageSize
        };

        // 关键排查步骤：打印请求参数
        console.log('请求参数对象:', params);

        // 将参数转换为JSON字符串查看格式
        const jsonParams = JSON.stringify(params);
        console.log('JSON格式参数:', jsonParams);

        const res = await students(params);
        console.log("接口返回:", res.data.list);


        this.tableData = res.data.list;
        this.total = res.data.total


    } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error('数据加载失败，请重试');

        // 打印详细的错误信息
        if (error.response) {
            console.log('响应状态:', error.response.status);
            console.log('响应数据:', error.response.data);
        }
    } finally {
        this.loading = false;
    }
}


export const handleSizeChange = async function (newSize) {
    this.pageSize = newSize;
    this.fetchData();
}

export const handleCurrentChange = async function (newPage) {
    this.pageNum = newPage;
    this.fetchData();
}



// 显示新增对话框
export const showAddDialog = async function (type, row) {
    this.dialogVisible = true;
    this.type = type;
    // 清空表单
    if (this.$refs.addForm) {
        this.$refs.addForm.resetFields();
    }
    if (type == 'add') {
        this.doTile = "新增用户"
    } else {
        this.doTile = "修改用户";
        // 将行数据赋值给表单
        this.addForm = {
            id: row.id,      // 确保包含id
            name: row.name,
            age: row.age,
            token: row.token
        };
    }

}

export const submitAddForm = async function () {
    this.$refs.addForm.validate(async (valid) => {
        if (valid) {
            try {
                // 准备JSON格式的请求数据
                const userInfo = {
                    'name': this.addForm.name,
                    'age': parseInt(this.addForm.age), // 确保年龄是数字
                    'token': this.addForm.token
                }

                console.log('准备提交的JSON数据:', JSON.stringify(userInfo, null, 2));

                // 调用API接口，以JSON格式发送数据
                const res = await addStudent(userInfo);

                console.log("新增用户返回:", res);
                this.$message.success('新增用户成功');
                this.dialogVisible = false;
                this.fetchData();

            } catch (error) {
                console.error("新增用户失败:", error);
                this.$message.error('新增用户失败: ' + (error.response?.data?.message || error.message));
            }
        }
    });
    this.dialogVisible = false;
}

export const submitUpdateForm = async function () {



    this.$refs.addForm.validate(async (valid) => {
        if (valid) {
            try {
                // 准备JSON格式的请求数据
                const userInfo = {
                    id: this.addForm.id,
                    'name': this.addForm.name,
                    'age': this.addForm.age, // 确保年龄是数字
                    'token': this.addForm.token
                }

                console.log('准备提交的JSON数据:', JSON.stringify(userInfo, null, 2));

                // 调用API接口，以JSON格式发送数据
                const res = await updateStudent(userInfo);

                console.log("修改用户返回:", res);
                this.$message.success('修改用户成功');
                this.dialogVisible1 = false;
                this.fetchData();

            } catch (error) {
                console.error("新增用户失败:", error);
                this.$message.error('新增用户失败: ' + (error.response?.data?.message || error.message));
            }
        }
    });
    this.dialogVisible = false;
}
export const handleSubmit = async function () {
    if (this.type === 'add') {
        this.submitAddForm();
    } else {
        this.submitUpdateForm();
    }
}

// 新增删除方法
export const handleDelete = async function (index, id) {

    try {
        // 确认对话框
        await this.$confirm(`确定要删除用户 "" 吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        // 调用删除API，传入姓名
        const res = await deleteStudent({ id: id });
        console.log("删除成功了：：", res)
        if (res.code === 200) {
            this.pageNum = 1;
            this.$message.success('删除成功');
            this.fetchData(); // 刷新列表
        } else {
            this.$message.error(res.message || '删除失败');
        }
    } catch (error) {
        if (error !== 'cancel') {  // 用户点击了取消
            console.error("删除失败:", error);
            this.$message.error('删除失败: ' + (error.response?.data?.message || error.message));
        }
    }
}


